<?php
/**
 *	KLF Framework
 *
 *	Written by Kristian Oye <kristianoye@gmail.com> on Oct 23, 2011
 *	Copyright (C) 2010-2011
 */
namespace KLF\System\Web\Routing
{
	use KLF\System\Web\MVC\KControllerContext;

	use KLF\System\KObject;
	use \KLF\System\KComponent;
	use \KLF\System\Web\IHttpHandler;
	use \KLF\System\Web\KHttpContext;
	use \KLF\System\IApplicationContext;
	use KLF\System\Web\MVC\KControllerFactory;
	
	/**
	 *  Class KMvcHandler
	 *
	 *  Responsible for creating the controller and dispatching the request.
	 *
	 *  @package KLF\System\Web\Routing
	 *  @access public
	 *  @author Kristian Oye <kristianoye@gmail.com>
	 *  @since 0.1
	 *  
	 *  @method KMvcHandler NewInstance
	 *  
	 *  @property-read KRouteContext $RouteContext The HTTP context under which the handler is running.
	 */	
	class KMvcHandler extends KObject implements IHttpHandler
	{
		/**
		 * Contains the route context under which the handler is running.
		 * 
		 * @var KRouteContext $_rpropRouteContext
		 */
		protected $_rpropRouteContext;
		
		/**
		 * Construct a new KMvcHandler object.
		 * 
		 * Enter description here ...
		 */
		public function __construct(KRouteContext $context)
		{
			$this->_rpropRouteContext = $context;
		}
		
		/**
		 * Returns true if the handler object is re-usable.
		 * 
		 * (non-PHPdoc)
		 * @see KLF\System\Web.IHttpHandler::GetIsReusable()
		 */
		public function GetIsReusable()
		{
			return false;
		}
		
		/**
		 * Returns a controller factory for brokering respects.
		 * 
		 * @return \KLF\System\Web\MVC\KDefaultControllerFactory
		 */
		public function GetControllerFactory()
		{
			return new KControllerFactory();
		}
		
		/**
		 * Dispatch the request for the application.
		 * 
		 * (non-PHPdoc)
		 * @see KLF\System\Web.IHttpHandler::ProcessRequest()
		 */
		public function ProcessRequest(KHttpContext $context)
		{
			$controllerName = $this->RouteContext->RouteData->GetRequiredString('controller');
			$controllerFactory = $this->GetControllerFactory();
			$controllerContext = new KControllerContext($this->_rpropRouteContext, $controllerName);
			$controller = $controllerFactory->CreateController($controllerContext);
			
			$controller->Execute(new KControllerContext($this->_rpropRouteContext, $controllerName, $controller));
		}
	}
}
